package com.tplhk.thread.threadlocal;

/**
 * @ClassName : TestThreadLocal
 * @Description : TODO
 * @Author : taiping
 * @Date: 2021/6/12 17:31
 **/
public class TestThreadLocal {

    private static ThreadLocal tl = new ThreadLocal<>();

    public void testThreadLocal1() {
        tl.set(1);
        System.out.println(String.format("当前线程名称: %s, main方法内获取线程内数据为: %s",
                Thread.currentThread().getName(), tl.get()));
        fc();
        // 父线程的变量是无法传递到子线程的
        new Thread(TestThreadLocal::fc).start();
    }

    public void testThreadLocal2() throws InterruptedException {
        tl.set(1);
        System.out.println(String.format("当前线程名称: %s, main方法内获取线程内数据为: %s",
                Thread.currentThread().getName(), tl.get()));
        fc();
        new Thread(() -> {
            // 父子两个线程的变量是独立的
            tl.set(2);
            fc();
        }).start();
        Thread.sleep(1000L);
        fc();
    }

    private static void fc() {
        System.out.println(String.format("当前线程名称: %s, fc方法内获取线程内数据为: %s",
                Thread.currentThread().getName(), tl.get()));
    }


    public static void main(String[] args) throws Exception {
        TestThreadLocal testThreadLocal = new TestThreadLocal();
//        testThreadLocal.testThreadLocal1();
        testThreadLocal.testThreadLocal2();
    }

}
